//
//  GZStatusViewModel.swift
//  sinaweibo
//
//  Created by mac book pro on 16/3/26.
//  Copyright © 2016年 finish. All rights reserved.
//

import UIKit
import SDWebImage
class GZStatusViewModel: NSObject {
    //MARK: -属性
    private var loadingStatus: Bool  = false
    static let sharedInstance = GZStatusViewModel()
    private override init() {
        super.init()
    }
    func loadStatus(since_id: Int64,max_id: Int64,callback:(statues: [GZStatus]?, error:NSError?)->()){
        if loadingStatus {
            let error2 = NSError(domain: "cn.istan.net, 正在加载数据呢,请扫等", code: 110, userInfo: nil)
            callback(statues: nil, error: error2)
            return
        }
       loadingStatus = true
        
        
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        var parameters: [String:AnyObject] = ["access_token":GZUserAccountViewModel.sharedInstance.userAccount!.access_token!]
        
        if since_id > 0{
            parameters["since_id"] = NSNumber(longLong: since_id)
        }else if max_id>0{
            // 比人传递了max_id.添加到字典里面
            parameters["max_id"] = NSNumber(longLong: max_id-1)
        }
        GZAFNetworkTool.sharedNetworkTool.requestGET(urlString, parameters: parameters) { (result, error) -> () in
          self.loadingStatus = false //加载完毕数据
            if error != nil{
                callback(statues: nil, error: error)
                return
            }
            if let array = result?["statuses"] as? [[String:AnyObject]]{
                var statuesArray = [GZStatus]() //定义空数组
                for dict in array{
                    let statues = GZStatus(dict: dict)
                    statuesArray.append(statues)
                }
                //                callback(statues: statuesArray, error: nil)
                //缓存图片
                self.cachedWebImage(
                    statuesArray , callback:callback)
            }else{
                callback(statues: nil, error: nil)
            }
            
        }
        
    }
    func cachedWebImage(statues: [GZStatus],callback:(statues: [GZStatus]?, error:NSError?)->()){
        //缓存图片的大小
        var length = 0.0
        //创建组
        let group = dispatch_group_create()
        
        //遍历模型
        for status in statues{
            var urls = [NSURL]()
            //原创微博是否有图
            if let pictureURLs = status.storePictureURLs{
                urls = pictureURLs
            }else{ //转发微博是否有图
                if let pictureURLs = status.retweeted_status?.storePictureURLs{
                    urls = pictureURLs
                }
            }
            //有图片，为1张的缓存 名称 urlMD5
            if urls.count == 1{
                let url = urls[0]
                dispatch_group_enter(group)
                SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (image, error, _, _, _) -> Void in
                    dispatch_group_leave(group)
                    if error != nil{
                        print("单张图片缓存失败")
                        return
                    }
                    let data = UIImagePNGRepresentation(image)!
                    length += Double(data.length)
                })
                
                
            }
        }
        //通知所有图片完成任务
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            let size = String(format: "%.2f", arguments: [length/1024/1024])
            print("单张图片缓存完毕大小:\(size)M")
            callback(statues: statues, error: nil)
        }
    }
}
